package cn.com.qmth.examcloud.websocket.service;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

/**
 * @author  	chenken
 * @date    	2018年2月1日 下午5:32:46
 * @company 	QMTH
 * @description MyWebSocket.java
 */
@ServerEndpoint(value = "/oewebsocket/{examRecordId}")
@Component
public class OeWebSocket {
	
	private static final Log log = LogFactory.getLog(OeWebSocket.class);
	
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<OeWebSocket> webSocketSet = new CopyOnWriteArraySet<OeWebSocket>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    
    private static Hashtable<String,Session> webSocketHashTable = new Hashtable<String, Session>();
    
    private String examRecordId;
    
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("examRecordId") String examRecordId,Session session){
    	log.info("examRecordId:"+examRecordId+",已建立连接");
        this.session = session;
        this.examRecordId = examRecordId;
        webSocketSet.add(this);
        webSocketHashTable.put(examRecordId,session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);  //从set中删除
        webSocketHashTable.remove(this.examRecordId);
        log.info("examRecordId:"+this.examRecordId+",已断开连接");
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
    	log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 发送消息
     * @param message
     * @throws IOException
     */
    public static void sendMessage(String key,String message) throws IOException {
        Set<String> keySet = webSocketHashTable.keySet();
        for (String _key : keySet) {
        	if(_key.equals(key)){
        		log.info("向key="+_key+"的客户端发送消息:"+message);
        		Session currSession = webSocketHashTable.get(key);
        		currSession.getBasicRemote().sendText(message);
        	}
        }
    }
    
    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        for (OeWebSocket item : webSocketSet) {
            try {
            	item.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                continue;
            }
        }
    }
    
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        OeWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        OeWebSocket.onlineCount--;
    }
}

